﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EAppointment.Models;
using System.Collections.Specialized;
using EAppointment.DataSets;
using EAppointment.DataSets.UserSetTableAdapters;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Threading;

namespace EAppointment.Controllers
{
    public class UserController : Controller
    {
        NameValueCollection HttpParams = System.Web.HttpContext.Current.Request.Params;

        // GET: /User/
        public JsonpResult Index()
        {
            return Errors.ReturnError(ErrorTypes.NOT_FOUND);
        }

        private UserSet.TB_BaseUserInfoDataTable GetUserInfo(string key)
        {
            try
            {
                UserSet.TB_BaseUserInfoDataTable table = new UserSet.TB_BaseUserInfoDataTable();
                TB_BaseUserInfoTableAdapter adapter = new TB_BaseUserInfoTableAdapter();
                return adapter.GetOneDataByKey(key);
            }
            catch
            {
                return null;
            }
        }

        private UserSet.TB_BaseUserInfoDataTable GetUserInfo(long id)
        {
            try
            {
                UserSet.TB_BaseUserInfoDataTable table = new UserSet.TB_BaseUserInfoDataTable();
                TB_BaseUserInfoTableAdapter adapter = new TB_BaseUserInfoTableAdapter();
                return adapter.GetDataByID(id);
            }
            catch
            {
                return null;
            }
        }

        [HttpPost]
        public JsonpResult Login()
        {
            string UserName = HttpParams["username"];
            if (string.IsNullOrWhiteSpace(UserName))
            {
                return Errors.ReturnError(ErrorTypes.PARAM_ERROR);
            }
            string Password = HttpParams["password"];
            byte[] md5Key = Encoding.Default.GetBytes(Password);
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();
            byte[] result = sha1.ComputeHash(md5Key);
            string sha1Key = BitConverter.ToString(result).Replace("-", "");

            UserSet.TB_BaseUserInfoDataTable table = GetUserInfo(UserName);

            if (table == null)
                return Errors.ReturnError(ErrorTypes.DB_ERROR);

            if (table.Count == 0)
            {
                return Errors.ReturnError(ErrorTypes.USER_NOT_EXISTED);
            }
            if (table[0].User_Status != 1)
            {
                return Errors.ReturnError(ErrorTypes.USER_NOT_AVALIABLE);
            }
            if (table[0].User_Password != sha1Key)
            {
                return Errors.ReturnError(ErrorTypes.VERIFY_FAILED);
            }

            HttpContext.Session["UserInfo"] = new BaseUserInfo(table[0]);
            return new JsonpResult(new UniResult
                {
                    Result = true,
                    Detail = new BaseUserInfo(table[0])
                });
        }

        [HttpPost]
        public JsonpResult Register()
        {
            string email = HttpParams["email"];
            string password = HttpParams["password"];
            string truename = HttpParams["truename"];
            string phone = HttpParams["phone"];
            if (string.IsNullOrWhiteSpace(email) ||
                string.IsNullOrWhiteSpace(password) ||
                string.IsNullOrWhiteSpace(truename) ||
                string.IsNullOrWhiteSpace(phone)
                )
            {
                return Errors.ReturnError(ErrorTypes.PARAM_ERROR);
            }
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] output = sha1.ComputeHash(Encoding.Default.GetBytes(password));
            password = BitConverter.ToString(output).Replace("-", "");
            TB_BaseUserInfoTableAdapter adapter = new TB_BaseUserInfoTableAdapter();
            int? result = 0;
            try
            {
                adapter.RegisterUser(email, phone, truename, password, ref result);
            }
            catch
            {
                return Errors.ReturnError(ErrorTypes.DB_ERROR);
            }
            if (result == -1)
            {

                return Errors.ReturnError(ErrorTypes.USER_EXISTED);
            }
            else
            {
                UserSet.TB_BaseUserInfoDataTable table = GetUserInfo(email);
                if (table.Count == 0)
                    return Errors.ReturnError(ErrorTypes.SERVER_ERROR);
                BaseUserInfo baseInfo = new BaseUserInfo(table[0]);
                EmailSender emailSender = new EmailSender(email, baseInfo);
                Thread mail = new Thread(emailSender.SendCode);
                mail.Start();
                return Succs.ReturnSuccess(SuccsTypes.REGISTER_SUCCESSED);
            }
        }

        public JsonpResult Verify(string p, string id)
        {
            UserSet.TB_BaseUserInfoDataTable table = new UserSet.TB_BaseUserInfoDataTable();
            long ID;
            long.TryParse(id, out ID);
            table = GetUserInfo(ID);

            if (table == null)
                return Errors.ReturnError(ErrorTypes.DB_ERROR);

            if (table.Count == 0)
            {
                return Errors.ReturnError(ErrorTypes.USER_NOT_EXISTED);
            }
            else if (table[0].User_Status == 1)
            {
                return Errors.ReturnError(ErrorTypes.USER_VERIFIED);
            }
            else if (table[0].User_Status == 0)
            {
                EmailVerfier verifier = new EmailVerfier(p, new BaseUserInfo(table[0]));
                if (verifier.DoVerify())
                    return Succs.ReturnSuccess(SuccsTypes.VERIFY_SUCCESSED);
                else
                    return Errors.ReturnError(ErrorTypes.VERIFY_FAILED);
            }
            else
            {
                return Errors.ReturnError(ErrorTypes.UNKNOWN_ERROR);
            }
        }

    }
}
